package com.dingding.gmall.order.service.impl;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.dingding.gmall.order.config.AlipayTemplate;
import com.dingding.gmall.order.entity.OrderEntity;
import com.dingding.gmall.order.entity.OrderItemEntity;
import com.dingding.gmall.order.service.OrderItemService;
import com.dingding.gmall.order.service.OrderService;
import com.dingding.gmall.order.service.PayOrderService;
import com.dingding.gmall.order.vo.PayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liugongding
 * @description:
 * @date 2022/4/1 4:06 PM
 */

@Service
public class PayOrderServiceImpl implements PayOrderService {

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Override
    public String pay(String orderSn) throws AlipayApiException {
        PayVo vo = new PayVo();
        OrderEntity orderEntity = orderService.getOrderStatus(orderSn);
        List<OrderItemEntity> list = orderItemService.getOrderItemList(orderSn);
        if (orderEntity != null) {
            String payAmount = orderEntity.getPayAmount().setScale(2, RoundingMode.UP).toString();
            vo.setTotalAmount(payAmount);
            vo.setOutTradeNo(orderSn);
            vo.setSubject("谷粒商城订单");
            vo.setBody(orderEntity.getBillContent());
            if (CollectionUtils.isNotEmpty(list)) {
                List<String> collect = list.stream().map(OrderItemEntity::getSkuName).collect(Collectors.toList());
                String subject = StringUtils.collectionToDelimitedString(collect, ";");
                vo.setSubject(subject+"订单");
            }
        }
        return alipayTemplate.pay(vo);
    }
}
